const fs = require('fs');
const path = require('path');
const uuid = require('uuid');

const { env } = require('../index');

function savedFile (file, keepFileName = false) {
    let now = new Date();
    let uploadedFilePath = env.uploadFiles || 'uploadFiles';
    let fileSavedDirectory = path.resolve(process.env.INIT_CWD || process.cwd(), uploadedFilePath);
    let subDirectory = path.resolve(fileSavedDirectory, `${now.getFullYear()}${now.getMonth() + 1}`);

    if (!fs.existsSync(fileSavedDirectory)) {
        fs.mkdirSync(fileSavedDirectory);
    }

    if (!fs.existsSync(subDirectory)) {
        fs.mkdirSync(subDirectory);
    }

    let newFileName = '';

    if (keepFileName) {
        newFileName = file.name || file.originalFilename;
    } else {
        let extName = path.extname((file.name || file.originalFilename));
        newFileName = `${uuid.v4()}${extName}`;
    }

    let result = {
        hash: file.hash,
        name: file.name || file.originalFilename,
        fullPath: `${uploadedFilePath}/${now.getFullYear()}${now.getMonth() + 1}/${newFileName}`
    };
    let filePath = path.join(subDirectory, newFileName);

    // 从临时目录中读取文件
    let reader = fs.createReadStream(file.path || file.filepath);
    let writer = fs.createWriteStream(filePath);

    reader.pipe(writer);

    return result;
}

module.exports = {
    upload: (ctx) => {
        let uploadedFile = {};
        let files = ctx.request.files || {};

        uploadedFile = savedFile(files.files, ctx.request.body && ctx.request.body.keepFileName);

        return uploadedFile;
    }
};